package com.qf.controller;

import com.qf.util.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author sunyamei
 * @version V1.0
 * @Project shirodemo
 * @Package com.qf.controller
 * @Description:
 * @Date 2022/7/19 20:52
 */
@RestController
public class UserController {
    @RequestMapping("/doLogin")
    public Result login(String username, String password,Boolean rememberMe){
//        System.out.println("username = " + username);
//        System.out.println("password = " + password);
        System.out.println("rememberMe = " + rememberMe);
        //1获取Subject对象
        Subject subject = SecurityUtils.getSubject();

        //防止空指针异常
        if(password==null){
            password="";
        }


        if(rememberMe==null){
            rememberMe=false;
        }
        //密码加密
        Md5Hash md5Hash=new Md5Hash(password,username,1024);
        System.out.println("加密后的密码："+md5Hash.toString());

        //2创建token  接收前端账户和密码信息
        UsernamePasswordToken token = new UsernamePasswordToken(username,md5Hash.toString(),rememberMe);

        //3开始登录
        try {
            subject.login(token);
            System.out.println("登录成功");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("未知账户异常");
        }  catch (LockedAccountException e) {
            e.printStackTrace();
            System.out.println("账户已锁定");
        }catch (CredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }

        //认证
//        System.out.println(subject.isAuthenticated()?"登录成功":"登录失败");
        //验证权限
        System.out.println(subject.hasRole("管理员")?"是管理员":"不是管理员");
        System.out.println(subject.isPermitted("sys:user:add")?"有添加用户的权限":"没有添加用户的权限");
        return Result.ok();//返回code状态 0 成功
    }

    @RequestMapping("/logout")
    public  Result loginout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return  Result.ok("退出成功");
    }
}
